import axios, { InternalAxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios';
import { message } from 'antd';
import { history } from 'umi';


const axiosInstance: AxiosInstance = axios.create({
    baseURL: 'http://localhost:3000/',
    timeout: 5000,
});

//请求拦截器
axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token');
    const admitRequest = localStorage.getItem('admitRequest');
    token ? config.headers.Authorization = token : null;
    admitRequest ? config.headers.admitRequest = admitRequest : null;
    return config;
}, (error) => {
    message.error(error);
    return Promise.reject(error);
});

// 添加响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.data.code === 500) {
            message.error(response.data.msg);
        }
        if (response.data.status == 401) {
            //token过期或者没传token 
            message.error(response.data.msg)
            localStorage.removeItem('token')
            window.location.href = "http://localhost:8000/";
        }
        if (response.data.status == 403) {
            //token过期或者没传token 
            message.error(response.data.msg)
        }
        return response.data;
    },
    (error) => {
        if (error.response && error.response.status === 404) {
            message.error('请求地址不存在');
        }
        return Promise.reject(error);
    }
);


export default axiosInstance;
